﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebDomain.Concrete;
using WebDomain.Entities;
using CZTopComputers.Models;

namespace CZTopComputers.Controllers
{
    [Authorize]
    public class TicketController : Controller
    {
        private EFTicketRepository ticketRepo;
        private EFTicketContainsRepository ticketContainsRepo;
        private EFProductRepository productRepository;
        private EFCustomPCRepository pcRepository;
        private int PageSize = 4;

        public TicketController()
        {
            ticketContainsRepo = new EFTicketContainsRepository();
            ticketRepo = new EFTicketRepository();
            productRepository = new EFProductRepository();
            pcRepository = new EFCustomPCRepository();
        }

        public ActionResult Index(int page = 1)
        {
            var viewModel = new TicketViewModel
            {
                Tickets = ticketRepo.Tickets
                .OrderBy(t => t.ID)
                .Skip((page-1)*PageSize)
                .Take(PageSize),
                TicketContains = ticketContainsRepo.TicketContains,
                Products = productRepository.Products,
                CustomPCs = pcRepository.CustomPCs,
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = ticketRepo.Tickets.Count()
                }
            };
            return View(viewModel);
        }

        
        public ActionResult Delete(int ticketID)
        {
            List<TicketContain> ticketContains = new List<TicketContain>();
            foreach (var tc in ticketContainsRepo.TicketContains.Where(x => x.TicketID == ticketID))
            {
                if (tc != null)
                    ticketContains.Add(tc);
            }
            ticketContainsRepo.RemoveTicketContains(ticketContains);
            ticketRepo.RemoveTicket(ticketRepo.Tickets.FirstOrDefault(t=>t.ID==ticketID));
            TempData["message"] = "Ticket of Id " + ticketID + " has been deleted";
            return RedirectToAction("Index");
        }

    }
}
